<?php

namespace app\webapi;

use think\exception\Handle;
use think\facade\Env;
use think\Response;
use Throwable;

class Exception extends Handle
{
    public $httpStatus = 500;

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        if (Env::get('APP_DEBUG') == false) {
            $message = $e->getMessage();
            if (!empty($e->getMessage())) {
                $tmpMsgArr = explode('--$_e_$--', $message);
                if (isset($tmpMsgArr[0]) && !empty($tmpMsgArr[0])) {
                    $message = $tmpMsgArr[0];
                }
            }
            // 添加自定义异常处理机制
            if (method_exists($e, "getStatusCode")) {
                $httpStatus = $e->getStatusCode();
            } else {
                $httpStatus = $this->httpStatus;
            }

            return show($e->getCode(), $message, [], $httpStatus);
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}